

#import "AutoRefreshTableHeaderView.h"
#import "AutoTableConstant.h"

//刷新所需高度
#define  RefreshViewHight 65.0
//执行动画时间
#define FLIP_ANIMATION_DURATION 0.18f
//上拉y坐标
#define  SCROLLVIEW_           (scrollView.contentSize.height < scrollView.frame.size.height ? scrollView.frame.size.height : scrollView.contentSize.height)

@interface AutoRefreshTableHeaderView ()
{
	id _delegate;
    
    //刷新状态
    UILabel *_statusLabel;
    //上次刷新时间
	UILabel *_lastUpdatedLabel;
    //正在刷新加载框
	UIActivityIndicatorView *_activityView;
    //刷新标识图片
	CALayer  *_arrowImage;
    
    //刷新状态，默认-可刷新-正在刷新
    AutoPullRefreshState _state;
    
    //刷新类型，上拉或者下拉
    PullStateStyle pullStateStyle;
}
//设置刷新状态
-(void)setState:(AutoPullRefreshState)aState;
@end

@implementation AutoRefreshTableHeaderView

@synthesize delegate=_delegate;

-(void)dealloc
{
	_delegate=nil;
    
    [_activityView release];
	_activityView = nil;
    
    [_statusLabel release];
	_statusLabel = nil;
	
    [_lastUpdatedLabel release];
	_lastUpdatedLabel = nil;
    
    _arrowImage = nil;
    [super dealloc];
}

//自定义初始化方法
- (id)initWithFrame:(CGRect)frame state:(PullStateStyle)state
{
    self = [super initWithFrame: frame];
    if (self) {
        
        //刷新类型，上拉或者下拉
        pullStateStyle = state;
        
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self setBackgroundColor:[UIColor clearColor]];
        
        _statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 48.0f, self.frame.size.width, 20.0f)];
        _statusLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _statusLabel.font = [UIFont boldSystemFontOfSize:13.0f];
        _statusLabel.textColor = TABEL_HIDE_REFRESH_STATE_COLOR;
        _statusLabel.shadowColor =[UIColor colorWithWhite:0.9f alpha:1.0f];
        _statusLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
        _statusLabel.backgroundColor = [UIColor clearColor];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_statusLabel];
        
        _lastUpdatedLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 30.0f, self.frame.size.width, 20.0f)];
        _lastUpdatedLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _lastUpdatedLabel.font = [UIFont systemFontOfSize:10.0f];
        _lastUpdatedLabel.textColor = TABEL_HIDE_REFRESH_TIME_COLOR;
        _lastUpdatedLabel.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
        _lastUpdatedLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
        _lastUpdatedLabel.backgroundColor = [UIColor clearColor];
        _lastUpdatedLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_lastUpdatedLabel];
                
        if(pullStateStyle == downPullState)
        {
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(25.0f, frame.size.height - 45.0f, 22.0f, 30.0f);
            layer.contentsGravity = kCAGravityResizeAspect;
            layer.contents = (id)[UIImage imageNamed:TABLE_REFRESH_ARROWIMAGE_NAME].CGImage;

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
            if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
                layer.contentsScale = [[UIScreen mainScreen] scale];
            }
#endif
            [[self layer] addSublayer:layer];
            _arrowImage=layer;
        }
        
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityView.frame = CGRectMake(25.0f, frame.size.height - 38.0f, 20.0f, 20.0f);
        [self addSubview:_activityView];
  		
        //初始设置为默认状态
		[self setState:AutoPullRefreshNormal];
    }
	
    return self;
}


#pragma mark - Setters
//设置刷新时间
- (void)refreshLastUpdatedDate
{
	//super是否需要显示时间
	if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceLastUpdated:)]) {
		
		NSDate *date = [_delegate egoRefreshTableHeaderDataSourceLastUpdated:self];
        
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
		_lastUpdatedLabel.text = [NSString stringWithFormat:@"上次刷新: %@", [formatter stringFromDate:date]];
        
		[[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"EGORefreshTableView_LastRefresh"];
		[[NSUserDefaults standardUserDefaults] synchronize];
		[formatter release];
		
	} else {
        
		_lastUpdatedLabel.text = nil;
//        [_statusLabel setCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height-RefreshViewHight/2)];
	}
}

//设置刷新状态
- (void)setState:(AutoPullRefreshState)aState
{
	switch (aState) {
		case AutoPullRefreshPulling:
        {
			//可以刷新
			_statusLabel.text = NSLocalizedString(@"松开即可更新...", @"松开即可更新...");
            if(pullStateStyle == downPullState)
            {
                [CATransaction begin];
                [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
                _arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
                [CATransaction commit];
            }
        }
			break;
		case AutoPullRefreshNormal:
        {
            //初始状态
			if (_state == AutoPullRefreshPulling) {
                if(pullStateStyle == downPullState)
                {
                    [CATransaction begin];
                    [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
                    _arrowImage.transform = CATransform3DIdentity;
                    [CATransaction commit];
                }
			}
            
            //拉取状态 NSString
            NSString *pullStateStyleString = nil;
			switch (pullStateStyle) {
                case onPullState:
                    pullStateStyleString = @"上拉加载更多...";
                    break;
                case downPullState:
                    pullStateStyleString = @"下拉获取数据";
                    break;
                default:
                    break;
            }
			_statusLabel.text = NSLocalizedString(pullStateStyleString, pullStateStyleString);
			[_activityView stopAnimating];
            if(pullStateStyle == downPullState)
            {
                [CATransaction begin];
                [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
                _arrowImage.hidden = NO;
                _arrowImage.transform = CATransform3DIdentity;
                [CATransaction commit];
            }
			
			[self refreshLastUpdatedDate];
        }
			break;
		case AutoPullRefreshLoading:
        {
            //正在刷新
			_statusLabel.text = NSLocalizedString(@"加载中...", @"加载中...");
			[_activityView startAnimating];
            if(pullStateStyle == downPullState)
            {
                [CATransaction begin];
                [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
                _arrowImage.hidden = YES;
                [CATransaction commit];
            }
        }
			break;
		default:
			break;
	}
	
	_state = aState;
}

/******     自动刷新数据      *****/
-(void)autoRefreshData:(UIScrollView*)scrollView
{
    //执行下拉动画
//    [UIView animateWithDuration:.3 animations:^(void){
        [scrollView setContentOffset:CGPointMake(0.0, -RefreshViewHight)];
        scrollView.contentInset = UIEdgeInsetsMake(RefreshViewHight, 0, 0, 0);
//    } completion:^(BOOL ss){
        //设置正在加载状态
        [self setState:AutoPullRefreshLoading];
        //执行刷新方法获取数据
        if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
            [_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
        }
//    }];
}

#pragma mark - ScrollView Methods
//手指屏幕上不断拖动调用此方法
- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.isDragging) {
		
        //是否正在刷新
		BOOL _loading = NO;
		if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
			_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
		}
        
        switch (pullStateStyle) {
            case onPullState:
            {
                //上拉
                if (_state == AutoPullRefreshPulling && (scrollView.contentOffset.y + (scrollView.frame.size.height)) < (SCROLLVIEW_ + RefreshViewHight) && scrollView.contentOffset.y > 0.0f && !_loading) {
                    //可刷新--初始状态
                    [self setState:AutoPullRefreshNormal];
                } else if (_state == AutoPullRefreshNormal && (scrollView.contentOffset.y + scrollView.frame.size.height) > (SCROLLVIEW_ + RefreshViewHight)  && !_loading) {
                    //初始状态--可刷新
                    [self setState:AutoPullRefreshPulling];
                }
            }
                break;
            case downPullState:
            {
                //下拉
                if (_state == AutoPullRefreshPulling && scrollView.contentOffset.y > -RefreshViewHight && scrollView.contentOffset.y < 0.0f && !_loading) {
                    //可刷新--初始状态
                    [self setState:AutoPullRefreshNormal];
                } else if (_state == AutoPullRefreshNormal && scrollView.contentOffset.y < -RefreshViewHight && !_loading) {
                    //初始状态--可刷新
                    [self setState:AutoPullRefreshPulling];
                }
            }
                break;
            default:
                break;
        }
        if (scrollView.contentInset.bottom != 0) {
            scrollView.contentInset = UIEdgeInsetsZero;
        }
	}
}

//当用户停止拖动，并且手指从屏幕中拿开的的时候调用此方法
- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
    
    //是否正在刷新
	BOOL _loading = NO;
	if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
		_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
	}
    
    //当前不在刷新,在该拉取状态下是否达到允许刷新状态
    BOOL isBool = NO;
    switch (pullStateStyle) {
        case onPullState:
        {
            //上拉
           	if (scrollView.contentOffset.y + (scrollView.frame.size.height) > SCROLLVIEW_ + RefreshViewHight && !_loading) {
                isBool = YES;
            }
        }
            break;
        case downPullState:
        {
            //下拉
            if (scrollView.contentOffset.y <= - RefreshViewHight && !_loading) {
                isBool = YES;
            }
        }
            break;
        default:
            break;
    }
    
    //可以刷新
    if (YES == isBool) {
        //设置为Loading状态
        [self setState:AutoPullRefreshLoading];
        
        [UIView animateWithDuration:.5 animations:^(void){
            switch (pullStateStyle) {
                case onPullState:
                {
                    //上拉
                    scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0f, (scrollView.contentSize.height < scrollView.frame.size.height ? scrollView.frame.size.height-scrollView.contentSize.height+RefreshViewHight : RefreshViewHight), 0.0f);
                }
                    break;
                case downPullState:
                {
                    //下拉
                    scrollView.contentInset = UIEdgeInsetsMake(RefreshViewHight, 0.0f, 0.0f, 0.0f);
                }
                    break;
                default:
                    break;
            }
        } completion:^(BOOL ss){
            //super执行刷新方法
            if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
                [_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
            }
        }];
    }
}

//当开发者页面页面刷新完毕调用此方法
- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView
{
    //执行下拉动画
    [UIView animateWithDuration:.3 animations:^(void){
        [scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
    } completion:^(BOOL ss){
        //显示初始状态
        [self setState:AutoPullRefreshNormal];
    }];
}

@end
